<script setup lang="js">
import { ref, onMounted } from 'vue'
import { debounce } from '@/utils/index.js';

const openNewTab = (url) => {
  chrome.tabs.create({ url })
}
// 大塔OA
const oaUrl = ref('https://oa.datalyg.com/#/plate')

const linkList = ref([
  {
    title: '智慧管廊',
    children: [
      { title: '预发布：', noLink: true }, // 非链接
      { title: '后台', url: 'https://www.yjgygl.com/stage/gl-admin/' },
      { title: '大屏', url: 'https://www.yjgygl.com/stage/gl-bigscreen/' },
      { title: '作业票h5', url: 'https://www.yjgygl.com/stage/gl-h5-zyp/' },

      { title: '生产：', noLink: true }, // 非链接
      { title: '后台', url: 'https://www.yjgygl.com/gl-admin/' },
      { title: '大屏', url: 'https://www.yjgygl.com/gl-bigscreen/' },
      { title: '作业票h5', url: 'https://www.yjgygl.com/gl-h5-zyp/' },

      { title: '测试：', noLink: true }, // 非链接
      { title: '后台', url: 'http://192.168.3.180:1280/' },
      { title: '大屏', url: 'http://192.168.3.180:1280/gl-bigscreen/' },
      // { title: '作业票h5', url: 'https://www.yjgygl.com/stage/gl-h5-zyp/' },
    ]
  },
  {
    title: '蒸汽管网',
    children: [
      { title: '预发布：', noLink: true }, // 非链接
      { title: '后台', url: 'http://192.168.3.180:1680/' },
      { title: '大屏', url: 'http://192.168.3.180:1680/3d/' },
      { title: '作业票h5', url: 'http://192.168.3.180:1680/stage/gl-h5-zyp' },

      { title: '生产：', noLink: true }, // 非链接
      { title: '后台', url: 'https://zqgw.yjgygl.com/#/login' },
      { title: '大屏', url: 'https://zqgw.yjgygl.com/3d/#/login'},
      { title: '作业票h5', url: 'https://zqgw.yjgygl.com/stage/gl-h5-zyp/' },
    ]
  },
  {
    title: '莱州管廊',
    children: [
      { title: '测试：', noLink: true }, // 非链接
      { title: '后台', url: 'http://192.168.3.180:2980/' },
      { title: '大屏', url: 'http://192.168.3.180:2980/gl-bigscreen/' },
      { title: '作业票h5', url: 'http://192.168.3.180:2980/gl-h5-zyp/' },
    ]
  },
  {
    title: '其他链接',
    children: [
      { title: 'Gitlab', url: 'http://192.168.3.196/' },
      { title: '小幺鸡', url: 'http://192.168.3.195:8088/' },
      { title: 'Jenkins', url: 'http://192.168.3.208:9090/' },
      { title: 'NAS', url: 'http://192.168.3.242:5000/#/signin' },
      { title: '长寿管廊', url: 'http://192.168.3.180:2780' }
    ]
  }
])

const openLink = (url) => {
  window.open(url)
}

// 把当前页面设置为暗黑模式（可切换）
const toggleDarkMode = async () => {
  try {
    // 获取当前活动标签页
    const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });

    if (!activeTab || !activeTab.id) {
      console.error('无法获取当前活动标签页');
      return;
    }

    // 为每个标签页生成唯一的样式key
    const styleKey = `dark-mode-${activeTab.id}`;

    // 要注入的CSS代码
    const css = `
      html {
        filter: invert(1) hue-rotate(180deg);
      }

      img,
      video,
      .logo,
      .icon {
        filter: invert(1) hue-rotate(180deg);
      }
    `;

    // 使用 chrome.storage.session 存储标签页的暗黑模式状态
    try {
      // 尝试获取当前标签页的暗黑模式状态
      const data = await chrome.storage.session.get(styleKey);
      const isDarkMode = data[styleKey] || false;

      if (isDarkMode) {
        // 当前是暗黑模式，需要切换回正常模式
        await chrome.scripting.removeCSS({
          target: { tabId: activeTab.id },
          css: css
        });
        // 更新状态
        await chrome.storage.session.set({ [styleKey]: false });
        console.log('暗黑模式已从当前网页移除');
      } else {
        // 当前是正常模式，需要切换为暗黑模式
        await chrome.scripting.insertCSS({
          target: { tabId: activeTab.id },
          css: css
        });
        // 更新状态
        await chrome.storage.session.set({ [styleKey]: true });
        console.log('暗黑模式已应用到当前网页');
      }
    } catch (storageError) {
      // 如果 storage.session 不可用，回退到简单的切换逻辑
      try {
        // 尝试移除样式，如果成功说明之前是暗黑模式
        await chrome.scripting.removeCSS({
          target: { tabId: activeTab.id },
          css: css
        });
        console.log('暗黑模式已从当前网页移除');
      } catch {
        // 移除失败说明之前不是暗黑模式，现在应用暗黑模式
        await chrome.scripting.insertCSS({
          target: { tabId: activeTab.id },
          css: css
        });
        console.log('暗黑模式已应用到当前网页');
      }
    }
  } catch (error) {
    console.error('切换暗黑模式失败:', error);
  }
}


// 添加一个响应式变量来跟踪编辑模式状态
const isEditableMode = ref(false)
// 切换是否为编辑模式
const toggleEditableMode = async () => {
  try {
    // 获取当前活动标签页
    const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });

    if (!activeTab || !activeTab.id) {
      console.error('无法获取当前活动标签页');
      return;
    }

    // 执行脚本切换可编辑模式
    const results = await chrome.scripting.executeScript({
      target: { tabId: activeTab.id },
      func: () => {
        // 切换contentEditable属性
        if (document.body.contentEditable === 'true') {
          document.body.contentEditable = 'false';
        } else {
          document.body.contentEditable = 'true';
        }
        return document.body.contentEditable;
      }
    });

    // 更新按钮显示状态
    if (results && results[0]) {
      isEditableMode.value = results[0].result === 'true';
    }
  } catch (error) {
    console.error('切换编辑模式失败:', error);
  }
}

// 检查当前标签页的编辑状态
const checkEditableMode = async () => {
  try {
    const [activeTab] = await chrome.tabs.query({ active: true, currentWindow: true });

    if (!activeTab || !activeTab.id) {
      isEditableMode.value = false;
      return;
    }

    const results = await chrome.scripting.executeScript({
      target: { tabId: activeTab.id },
      func: () => {
        return document.body.contentEditable;
      }
    });

    if (results && results[0]) {
      isEditableMode.value = results[0].result === 'true';
    }
  } catch (error) {
    console.error('检查编辑模式失败:', error);
    isEditableMode.value = false;
  }
}

// 加入防抖函数
const debounceDark = debounce(toggleDarkMode)
const debounceEditable = debounce(toggleEditableMode)

// 组件挂载时检查当前编辑状态
onMounted(() => {
  checkEditableMode();
})
</script>

<template>
  <div style="text-align: center;width: 260px;">
    <el-button type="primary" @click="openNewTab('crypt.html')">加解密</el-button>
    <el-button @click="openNewTab('settings.html')">配置项</el-button>
    <el-button type="warning" @click="openLink(oaUrl)">大塔OA</el-button>

    <template v-for="item in linkList">
      <h5>{{ item.title }}</h5>
      <el-row>
        <el-col :span="6" v-for="(cell, index) in item.children" :key="index">
          <el-link :underline="false" type="info" v-if="cell.noLink">{{ cell.title }}</el-link>
          <el-link type="primary" @click="openLink(cell.url)" v-else>{{ cell.title }}</el-link>
        </el-col>
      </el-row>
    </template>

    <h5>其他小功能测试</h5>
    <el-row>
      <el-tooltip
        class="box-item"
        effect="dark"
        content="切换暗黑模式/正常模式；暗黑模式是自己写的硬css，标准化暗黑模式还需要网站内部写"
      >
        <el-button @click="debounceDark">暗黑模式</el-button>
      </el-tooltip>
      <el-tooltip
        class="box-item"
        effect="dark"
        content="当前网页切换是否为可编辑模式"
        placement="top-start"
      >
        <el-button @click="debounceEditable">
          {{ isEditableMode ? '还原编辑' : '编辑模式' }}
        </el-button>
      </el-tooltip>
    </el-row>
  </div>
</template>

<style scoped>
h5 {
  margin-top: 16px;
  margin-bottom: 4px;
}
</style>
